package com.pi.tcp.main;


import java.sql.SQLException;

import com.pi.tcp.handler.WifiLockHander;
import com.pi.tcp.hook.ShutDownHook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.SelfSignedCertificate;

public class LockServer {

    private static final Logger logger = LoggerFactory.getLogger(LockServer.class);

    private final int port;
    //private SocketChannel socketChannel;
    static final boolean SSL = System.getProperty("ssl") != null;

    public LockServer(int port) throws Exception {
        this.port = port;
        bind();
    }

    private void bind() throws Exception {

        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } else {
            sslCtx = null;
        }

        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            Runtime.getRuntime().addShutdownHook(new Thread(new ShutDownHook(bootstrap)));
            bootstrap.group(boss, worker);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline p = socketChannel.pipeline();
                    if (sslCtx != null) {
                        p.addLast(sslCtx.newHandler(socketChannel.alloc()));
                    }
//					p.addLast("byteDecode",new ByteDecoder());
//					p.addLast("LockHander",new LockHander());
                    p.addLast("wifiLockHander", new WifiLockHander());
                    //p.addLast("HeartBeatRespHandler", new HeartBeatRespHandler());
                }
            });
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            bootstrap.option(ChannelOption.SO_RCVBUF, 1024 * 256);
            bootstrap.option(ChannelOption.SO_SNDBUF, 1024 * 256);
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            ;

            ChannelFuture f = bootstrap.bind(port).sync();
            //f.addListener(ChannelFutureListener.CLOSE);
            if (f.isSuccess()) {
                logger.info("LOCK SERVER START---------------");
            }
            f.channel().closeFuture().sync();

        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        try {
            new LockServer(8899);
        } catch (SQLException e) {
            logger.error("启动失败", e);
        }
    }
}
